﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using CityLife.CityService;
using System.ServiceModel;
using System.Windows.Browser;
using System.Windows.Threading;
using CityLife.GameLogic;
using Facebook.Rest;
using Facebook.Session;
using System.Collections.Generic;
using Facebook.Utility;
using CityLife.Controls;




namespace CityLife
{
	public partial class MainPage : UserControl
	{


        
        public static CityHeart Heart = new CityHeart();
        public static CityEditor Editor = new CityEditor();

        public static bool BuildOK { get; set; }

        private Point _last = new Point();
        private bool _mouseDown = false;
        public long UserID =0;
 

        private void OnMouseWheel(object sender, HtmlEventArgs args)
        {
            double mouseDelta = 0;
            ScriptObject e = args.EventObject;
            // Mozilla and Safari
            if (e.GetProperty("detail") != null)
            {
                mouseDelta = ((double)e.GetProperty("detail"));
            }
            // IE and Opera
            else if (e.GetProperty("wheelDelta") != null)
                mouseDelta = ((double)e.GetProperty("wheelDelta"));

            mouseDelta = Math.Sign(mouseDelta);

            CityScale.ScaleX = CityScale.ScaleX + mouseDelta/25;
            CityScale.ScaleY = CityScale.ScaleY + mouseDelta/25;

            WindowCanvasCityScale.ScaleX = CityScale.ScaleX + mouseDelta / 25;
            WindowCanvasCityScale.ScaleY = CityScale.ScaleY + mouseDelta / 25;

            


        }




        public static  Api _facebookAPI;
        private readonly BrowserSession _browserSession;
        private const string ApplicationKey = "78186aef844024149ad28f7faa661fe9"; 


		public MainPage()
		{
            InitializeComponent();
           
           


            Share.Click += new RoutedEventHandler(Share_Click);

          
			HtmlPage.Document.AttachEvent("oncontextmenu", this.OnContextMenu);
            HtmlPage.Window.AttachEvent("DOMMouseScroll", OnMouseWheel); // Mozilla
            HtmlPage.Window.AttachEvent("onmousewheel", OnMouseWheel);
            HtmlPage.Document.AttachEvent("onmousewheel", OnMouseWheel); // IE
          

            ToolBoxLayer.MouseEnter += new MouseEventHandler(ToolBoxLayer_MouseEnter);
            ToolBoxLayer.MouseLeave += new MouseEventHandler(ToolBoxLayer_MouseLeave);
            //facebook



            this.UserID = ApplicationState.Current.CurrentFacebookSession.UserID;


          
        
            Heart.SplashLogin = SplashLogin;
            Heart.UserID = UserID;
            Heart.Dispatcher = Dispatcher;
           
            Editor = new CityEditor();
            Heart.CityEditor = Editor;
            Heart.SaveIndicator = SaveIndicator;
            Heart.CashView = Score.CashView;
            Heart.PointsView = Score.PointsView;
            Heart.PopulationView = Score.PopulationView;
            Heart.CityClock = GameClock;
            Heart.ElementInformation = ElementInformation;
            Heart.FriendsListbox = FriendsListbox;

          
             Editor.SaveIndicator = SaveIndicator;
             Editor.CityCanvas.Canvas = CityCanvas;
           
           //  Editor.CityCanvas.GlobalCanvas = CityGlobalCanvas;
             Editor.CityGrid = CityGrid;
             Editor.ElementInformation = ElementInformation;
             Heart.CityCanvas = Editor.CityCanvas;
             Heart.WindowCityCanvas =this.WindowCanvas;

            // Required to initialize variables
            InitGrid();

           // Heart.LoadCity(null);
            #region login to facebook
            /*
            FBDialog fbdialog = null;
            if (fbdialog == null)
            {
                fbdialog = new FBDialog();
                fbdialog.Width = 400;
                fbdialog.Height = 400;
                fbdialog.HorizontalAlignment = HorizontalAlignment.Center;
                fbdialog.VerticalAlignment = VerticalAlignment.Center;
            }
            fbdialog.Title = "Facebook Connect";
            fbdialog.HorizontalOffset = (double)App.Current.Host.Content.ActualWidth / 2d - fbdialog.Width / 2;
            fbdialog.VerticalOffset = (double)App.Current.Host.Content.ActualHeight / 2d - fbdialog.Height / 2; ;
            fbdialog.ShowDialog();

            */



            
            _browserSession = new BrowserSession(ApplicationKey);
            _browserSession.LoginCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(_browserSession_LoginCompleted);

           _browserSession.Login();
             
            #endregion

            //UserID = 100000217572082;


			
			
 
			
         
          
		
         
        }

        void Share_Click(object sender, RoutedEventArgs e)
        {

           // MainPage._facebookAPI.Application.Permissions;
        
            List<Facebook.Schema.action_link> links = new List<Facebook.Schema.action_link>();

         Facebook.Schema.action_link join =    new Facebook.Schema.action_link();
            join.href="http://metropoline.zapto.org/City.aspx";
            join.text="Join";
            links.Add(join);

            MainPage._facebookAPI.Stream.PublishAsync("Publishing to stream with attachment", null, links, null,0, AsyncShareCompleted, null); 

 

       }

 

        public void AsyncShareCompleted(string result, Object state, FacebookException e)
        {
            var actual = result;
        }


        void _browserSession_LoginCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (_facebookAPI == null)
            {
                _facebookAPI = new Api(_browserSession);

                Heart.UserID = _facebookAPI.Session.UserId;


                Heart.LoadCity(null);
                //MainPage._facebookAPI.Friends.GetUserObjectsAsync(new Users.GetInfoCallback(MainPage.Heart.GetAppUserObjectsCompleted), null);
              

            }

        }

		
	 



			
        void ToolBoxLayer_MouseLeave(object sender, MouseEventArgs e)
        {
            if(!DesignSelector.IsOpened)
                    (sender as UserControl).Opacity = 0.1;
        }

        void ToolBoxLayer_MouseEnter(object sender, MouseEventArgs e)
        {
            (sender as UserControl).Opacity = 1;
     
        }

        void ToggleFullScreenBTN_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Host.Content.IsFullScreen = !System.Windows.Application.Current.Host.Content.IsFullScreen;
        }
   


        #region movement
        void CityCanvas_MouseMove(object sender, MouseEventArgs e)
        {
          
            Point current = e.GetPosition(null);

            if (_mouseDown)
            {
                Editor.Dragging = true;

      

                //newPosition = new Point();
                //newPosition.X = (double)CityCanvas.GetValue(Canvas.LeftProperty) + (current.X - _last.X);
                //newPosition.Y = (double)CityCanvas.GetValue(Canvas.TopProperty) + (current.Y - _last.Y);

                double Yaxe = CityCanvas.Margin.Top +(current.Y - _last.Y);
                double Xaxe = CityCanvas.Margin.Left + (current.X - _last.X);


                Thickness pad = new Thickness();
                pad.Top = Yaxe;
                pad.Left = Xaxe;
                CityCanvas.Margin = pad;
           //     CityCanvas.SetValue(Canvas.LeftProperty, newPosition.X);
            //    CityCanvas.SetValue(Canvas.TopProperty, newPosition.Y);
            }           

            _last = current;




        }

        void CityCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //CityGrid.CaptureMouse();
            _mouseDown = true;
        }

 



        private void PrespectiveSliderX_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            CityPerspective.RotationX = e.NewValue * -1;
        }

        private void PrespectiveSliderY_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            CityPerspective.RotationY = e.NewValue;
        }

        private void zone_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ShowInfo((sender as ICityElement));
        }

        public void ShowInfo(ICityElement elem)
        {
            Dialog CityDialog = new Dialog();
            CityDialog.AttachElement(elem);
            CityDialog.Show();

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            CityScale.ScaleX = CityScale.ScaleX + 0.1;
            CityScale.ScaleY = CityScale.ScaleY + 0.1;

            WindowCanvasCityScale.ScaleX = CityScale.ScaleX + 0.1;
            WindowCanvasCityScale.ScaleY = CityScale.ScaleY + 0.1;

            

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            CityScale.ScaleX = CityScale.ScaleX - 0.1;
            CityScale.ScaleY = CityScale.ScaleY - 0.1;

            WindowCanvasCityScale.ScaleX = CityScale.ScaleX - 0.1;
            WindowCanvasCityScale.ScaleY = CityScale.ScaleY - 0.1;
            
        }
    

        private void OnContextMenu(object sender, System.Windows.Browser.HtmlEventArgs e)
        {
          

            //e.PreventDefault();
        }

        void CityCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _mouseDown = false;
            Editor.Dragging = false;
            //CityCanvas.ReleaseMouseCapture();

        }

        #endregion



 
		private void InitGrid()
		{
            CityCanvas.MouseLeftButtonDown += new MouseButtonEventHandler(CityCanvas_MouseLeftButtonDown);
            CityCanvas.MouseLeftButtonUp += new MouseButtonEventHandler(CityCanvas_MouseLeftButtonUp);
            CityCanvas.MouseMove += new MouseEventHandler(CityCanvas_MouseMove);

 
 
			for(int columns =0;columns< CityGrid.ColumnDefinitions.Count;columns++)
			{
				
				for(int rows =0;rows< CityGrid.RowDefinitions.Count;rows++)
			{
                Empty empty = new Empty(); 
                empty.MouseLeftButtonUp += new MouseButtonEventHandler(CityCursor_MouseLeftButtonUp);
                empty.SetValue(Grid.ColumnProperty, columns);
                empty.SetValue(Grid.RowProperty, rows);
                empty.Name = "Empty_" + columns.ToString() + "_" + rows.ToString();
                CityGrid.Children.Add(empty);
			}
				
				
				
				
			}

			
			 
			
			
		}

        void CityCursor_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Editor.HandleCityClick(sender, e);
        }


    

                private void CityGrid_MouseMove(object sender, MouseEventArgs e)
        {
        
                    Editor.CreateCursor( sender,  e);

        }

        private void CityGrid_MouseLeave(object sender, MouseEventArgs e)
        {

            Editor.CreateCursor(sender, e);

        }

        private void StartCam_Click(object sender, RoutedEventArgs e)
        {


            Recorder recorderWindow = new Recorder();
            recorderWindow.ShowDialog();


        }


 


     


		 
	}
}